package fr.fermat.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import fr.fermat.databaseManager.Lyrics;
import fr.fermat.lyricsext.LyricServiceListener;
import fr.fermat.lyricsext.MainActivity;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class LyricService extends Service {

	protected final IBinder iBinder = new LocalBinder();
	private static String URL = "http://78.43.139.86/index_.php";

	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return  this.iBinder;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		Log.d("LyricService", "service created");
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.d("LyricService", "service unbind");
		super.onUnbind(intent);
		return true;
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * the Service binder
	 */
	public class LocalBinder extends Binder {

		public LyricService getService() {

			return LyricService.this;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startid) {
		// code to execute when the service is starting up
		Log.d("LyricService", "service started");
		return START_STICKY;

	}
	/**
	 *  take the lyric from the Server
	 * @param l
	 * @return  the lyric in JSON format if success or error message
	 */ 
	 
	public String  getLyricsFromServer (Lyrics l, final LyricServiceListener listener,
			final Activity activity) {
		
		String infoLyr = "";
		JSONObject json = new JSONObject();
				
		try {
			json.put("artist", l.getArtist().toLowerCase());
			json.put("track", l.getTrack().toLowerCase());
			json.put("album", l.getAlbum().toLowerCase());
			json.put("lyric", l.getLyric());
			
	        HttpPost request = new HttpPost(URL);
	        request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
	        request.setHeader("json", json.toString());
			
	        DefaultHttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String  response = httpClient.execute(request,responseHandler);
			
			infoLyr = ExtractLyricFromJSONData(response, activity);
			activity.runOnUiThread(new Runnable() {

										public void run() {
											Log.d("LyricService",
													"in runOnUiThread");
											listener.onRequestFinished();
										}
									});
			
		} catch (final JSONException e) {
			// TODO Auto-generated catch block
			Log.e("Service", e.getMessage());
			activity.runOnUiThread(new Runnable() {

				public void run() {
					Log.d("LyricService",
							"in runOnUiThread");
					listener.onRequestFinished();
				}
			});
			MainActivity.RunToMe(e.getMessage(), activity);
		} catch (final UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			Log.e("Service", e.getMessage());
			activity.runOnUiThread(new Runnable() {

				public void run() {
					Log.d("LyricService",
							"in runOnUiThread");
					listener.onRequestFinished();
				}
			});
			MainActivity.RunToMe(e.getMessage(), activity);
			
		}catch (final ClientProtocolException e) {
			// TODO Auto-generated catch block
			Log.e("Service", e.getMessage());
			activity.runOnUiThread(new Runnable() {

				public void run() {
					Log.d("LyricService",
							"in runOnUiThread");
					listener.onRequestFinished();
				}
			});
			MainActivity.RunToMe(e.getMessage(), activity);
         }catch (final IOException e) {
			// TODO Auto-generated catch block
			Log.e("Service", e.getMessage());
			activity.runOnUiThread(new Runnable() {

				public void run() {
					Log.d("LyricService",
							"in runOnUiThread");
					listener.onRequestFinished();
				}
			});
			MainActivity.RunToMe(e.getMessage(), activity);
			}
       
		return infoLyr ;
		
	}
	/**
	 *  save lyric to Server
	 * @param l
	 * @return   Save Information 
	 */
	public void sendLyricsToServer (Lyrics l, final Activity activity) {
		
		JSONObject json = new JSONObject();
		try {
			json.put("artist", l.getArtist().toLowerCase());
			json.put("track", l.getTrack().toLowerCase());
			json.put("album", l.getAlbum().toLowerCase());
			json.put("lyric", l.getLyric());
			
			HttpPost request = new HttpPost(URL);
	        request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
	        request.setHeader("json", json.toString());
			
	        DefaultHttpClient httpClient = new DefaultHttpClient();
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
			final String  response = httpClient.execute(request,responseHandler);
			MainActivity.RunToMe(response, activity);
			
			
		}catch (final JSONException e) {
			// TODO Auto-generated catch block
			MainActivity.RunToMe(e.getMessage(), activity);
		} catch (final UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
    		MainActivity.RunToMe(e.getMessage(), activity);
		}catch (final ClientProtocolException e) {
			// TODO Auto-generated catch block
			MainActivity.RunToMe(e.getMessage(), activity);
		} catch (final IOException e) {
			// TODO Auto-generated catch block
			MainActivity.RunToMe(e.getMessage(), activity);
		}
	}
	/**
	 * Extract Informations of Lyric from the JSON Data
	 * @param jsonData
	 * @return
	 */
	private String ExtractLyricFromJSONData (String jsonData, final Activity activity) {
		String Info_Extract = "";
		if (jsonData != null) {
			try {
				JSONObject json = new JSONObject(jsonData);
				JSONObject info = json.getJSONObject("info");

				Log.i("json_info", info.toString());

				if (info.getString("success") != null) {
					String res = info.getString("success");
					if (Integer.parseInt(res) == 1) {
						JSONObject lyric = info.getJSONObject("artist");
						Log.i("json_lyric", lyric.toString());
						Info_Extract = lyric.getString("lyric");
						MainActivity.RunToMe("Lyric get from Server : Succes", activity);
					} else if (info.getString("error") != null) {
						res = info.getString("error");
						if (Integer.parseInt(res) == 1) {
							MainActivity.RunToMe("Lyric get from Server : Error", activity);
							String error_msg = info.getString("error_msg");
							Log.i("error_msg", error_msg);
							Info_Extract = error_msg;
						}
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG); 
			}
		} else {
			Info_Extract = "Server no in Service";
		}
		
		return Info_Extract;
    }
	
}
